package com.atao.service.impl;

import com.atao.constants.SystemConstant;
import com.atao.domain.Result;
import com.atao.enums.HttpCodeEnums;
import com.atao.service.UploadService;
import com.atao.utils.ImageUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UploadServiceImpl implements UploadService {

    /**
     * 上传图片
     * @param img MultipartFile
     * @return 可回显
     */
    @Override
    public Result uploadImg(MultipartFile img) {
        String originalFilename = img.getOriginalFilename();
        if (!isImg(originalFilename)) {
            return Result.fail(HttpCodeEnums.FILE_TYPE_ERROR.getMsg());
        }
        String key = SystemConstant.BLOG_IMG_PATH + UUID.randomUUID().toString().replaceAll("-", "")+
                originalFilename;
        uploadOss(img, key);
        return Result.ok(SystemConstant.BLOG_OSS_URL + key);
    }

    /**
     * 上传文件
     */
    @Override
    public Result uploadFile(File file) {
        String key = SystemConstant.BLOG_IMG_PATH + "local-search.xml";
        uploadOss(file, key);
        return Result.ok(SystemConstant.BLOG_OSS_URL + key);
    }

    //判断文件类型
    private boolean isImg(String fileName) {
        String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.png|.gif)$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(fileName);
        return matcher.find();
    }

    //删除oss
    @Override
    public void deleteOss(String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释

        String accessKey = "utSjRMbJClRMCAep_npTwLb6eFq1eU4G-BB1A14O";
        String secretKey = "iTZ5aT8GB7aaYCfcPYS6sRejrmUSVZLO0XOG5cBC";
        String bucket = "atao-blog-1";

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, filePath);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }


    }

    //上传oss
    private void uploadOss(InputStream inputStream, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "utSjRMbJClRMCAep_npTwLb6eFq1eU4G-BB1A14O";
        String secretKey = "iTZ5aT8GB7aaYCfcPYS6sRejrmUSVZLO0XOG5cBC";
        String bucket = "atao-blog-1";

        //默认不指定key的情况下，以文件内容的hash值作为文件名

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
//            InputStream inputStream = file.getInputStream();


            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            //压缩
            if (!filePath.endsWith(".xml")) {
                inputStream = ImageUtils.compressPicByQuality(inputStream);
            }
            try {
                Response response = uploadManager.put(inputStream, filePath,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
    }

    private void uploadOss(MultipartFile file, String filePath) {
        try {
            uploadOss(file.getInputStream(), filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void uploadOss(File file, String filePath) {
        try {
            uploadOss(new FileInputStream(file), filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
